import 'package:flutter/cupertino.dart';
import 'package:macos_ui/macos_ui.dart';
import '../models/mcp_tool.dart';

/// 参数表单组件
class ParameterForm extends StatefulWidget {
  final McpTool? tool;
  final Map<String, dynamic> parameters;
  final ValueChanged<MapEntry<String, dynamic>> onParameterChanged;
  final VoidCallback onSubmit;
  final bool isLoading;

  const ParameterForm({
    super.key,
    this.tool,
    required this.parameters,
    required this.onParameterChanged,
    required this.onSubmit,
    this.isLoading = false,
  });

  @override
  State<ParameterForm> createState() => _ParameterFormState();
}

class _ParameterFormState extends State<ParameterForm> {
  final Map<String, TextEditingController> _controllers = {};

  @override
  void initState() {
    super.initState();
    _initializeControllers();
  }

  @override
  void didUpdateWidget(ParameterForm oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.tool?.name != widget.tool?.name) {
      _disposeControllers();
      _initializeControllers();
    }
  }

  void _initializeControllers() {
    if (widget.tool == null) return;

    for (final param in widget.tool!.parameters) {
      final controller = TextEditingController();
      final value = widget.parameters[param.name];
      if (value != null) {
        controller.text = value.toString();
      } else if (param.defaultValue != null) {
        controller.text = param.defaultValue.toString();
      }
      _controllers[param.name] = controller;
    }
  }

  void _disposeControllers() {
    for (final controller in _controllers.values) {
      controller.dispose();
    }
    _controllers.clear();
  }

  @override
  void dispose() {
    _disposeControllers();
    super.dispose();
  }

  dynamic _parseValue(String value, String type) {
    if (value.isEmpty) return null;

    try {
      switch (type) {
        case 'number':
        case 'integer':
          return num.parse(value);
        case 'boolean':
          return value.toLowerCase() == 'true' || value == '1';
        case 'array':
          // Simple array parsing: comma-separated values
          return value.split(',').map((e) => e.trim()).toList();
        case 'object':
          // For simplicity, we'll just pass the string
          // In production, you'd want proper JSON parsing
          return value;
        default:
          return value;
      }
    } catch (e) {
      return value;
    }
  }

  Widget _buildParameterField(McpToolParameter param) {
    final controller = _controllers[param.name];
    if (controller == null) return const SizedBox.shrink();

    if (param.type == 'boolean') {
      return _buildBooleanField(param);
    } else if (param.enumValues != null && param.enumValues!.isNotEmpty) {
      return _buildEnumField(param);
    } else if (param.type == 'array' || param.type == 'object') {
      return _buildTextAreaField(param, controller);
    } else {
      return _buildTextField(param, controller);
    }
  }

  Widget _buildBooleanField(McpToolParameter param) {
    final value = widget.parameters[param.name] as bool? ?? false;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              param.name,
              style: MacosTheme.of(
                context,
              ).typography.body.copyWith(fontWeight: FontWeight.w500),
            ),
            if (param.required)
              Text(' *', style: TextStyle(color: MacosColors.systemRedColor)),
          ],
        ),
        const SizedBox(height: 8),
        MacosCheckbox(
          value: value,
          onChanged: (newValue) {
            widget.onParameterChanged(MapEntry(param.name, newValue ?? false));
          },
        ),
        if (param.description != null && param.description!.isNotEmpty) ...[
          const SizedBox(height: 4),
          Text(
            param.description!,
            style: MacosTheme.of(context).typography.caption1.copyWith(
              color: MacosTheme.of(
                context,
              ).typography.body.color?.withOpacity(0.6),
            ),
          ),
        ],
      ],
    );
  }

  Widget _buildEnumField(McpToolParameter param) {
    final value =
        widget.parameters[param.name]?.toString() ?? param.enumValues!.first;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              param.name,
              style: MacosTheme.of(
                context,
              ).typography.body.copyWith(fontWeight: FontWeight.w500),
            ),
            if (param.required)
              Text(' *', style: TextStyle(color: MacosColors.systemRedColor)),
          ],
        ),
        const SizedBox(height: 8),
        MacosPopupButton<String>(
          value: value,
          onChanged: (newValue) {
            if (newValue != null) {
              widget.onParameterChanged(MapEntry(param.name, newValue));
            }
          },
          items: param.enumValues!
              .map((e) => MacosPopupMenuItem(value: e, child: Text(e)))
              .toList(),
        ),
        if (param.description != null && param.description!.isNotEmpty) ...[
          const SizedBox(height: 4),
          Text(
            param.description!,
            style: MacosTheme.of(context).typography.caption1.copyWith(
              color: MacosTheme.of(
                context,
              ).typography.body.color?.withOpacity(0.6),
            ),
          ),
        ],
      ],
    );
  }

  Widget _buildTextAreaField(
    McpToolParameter param,
    TextEditingController controller,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              param.name,
              style: MacosTheme.of(
                context,
              ).typography.body.copyWith(fontWeight: FontWeight.w500),
            ),
            if (param.required)
              Text(' *', style: TextStyle(color: MacosColors.systemRedColor)),
            const SizedBox(width: 8),
            Text(
              '(${param.type})',
              style: MacosTheme.of(context).typography.caption1.copyWith(
                color: MacosTheme.of(
                  context,
                ).typography.body.color?.withOpacity(0.5),
              ),
            ),
          ],
        ),
        if (param.description != null && param.description!.isNotEmpty) ...[
          const SizedBox(height: 4),
          Text(
            param.description!,
            style: MacosTheme.of(context).typography.caption1.copyWith(
              color: MacosTheme.of(
                context,
              ).typography.body.color?.withOpacity(0.6),
            ),
          ),
        ],
        const SizedBox(height: 8),
        MacosTextField(
          controller: controller,
          placeholder: param.type == 'array' ? '输入逗号分隔的值' : '输入 ${param.type}',
          maxLines: 4,
          onChanged: (value) {
            widget.onParameterChanged(
              MapEntry(param.name, _parseValue(value, param.type)),
            );
          },
        ),
      ],
    );
  }

  Widget _buildTextField(
    McpToolParameter param,
    TextEditingController controller,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              param.name,
              style: MacosTheme.of(
                context,
              ).typography.body.copyWith(fontWeight: FontWeight.w500),
            ),
            if (param.required)
              Text(' *', style: TextStyle(color: MacosColors.systemRedColor)),
            const SizedBox(width: 8),
            Text(
              '(${param.type})',
              style: MacosTheme.of(context).typography.caption1.copyWith(
                color: MacosTheme.of(
                  context,
                ).typography.body.color?.withOpacity(0.5),
              ),
            ),
          ],
        ),
        if (param.description != null && param.description!.isNotEmpty) ...[
          const SizedBox(height: 4),
          Text(
            param.description!,
            style: MacosTheme.of(context).typography.caption1.copyWith(
              color: MacosTheme.of(
                context,
              ).typography.body.color?.withOpacity(0.6),
            ),
          ),
        ],
        const SizedBox(height: 8),
        MacosTextField(
          controller: controller,
          placeholder: '输入 ${param.name}',
          onChanged: (value) {
            widget.onParameterChanged(
              MapEntry(param.name, _parseValue(value, param.type)),
            );
          },
        ),
      ],
    );
  }

  bool _validateParameters() {
    if (widget.tool == null) return false;

    for (final param in widget.tool!.parameters) {
      if (param.required) {
        final value = widget.parameters[param.name];
        if (value == null ||
            (value is String && value.isEmpty) ||
            (value is List && value.isEmpty)) {
          return false;
        }
      }
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    if (widget.tool == null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              CupertinoIcons.arrow_left,
              size: 48,
              color: MacosTheme.of(
                context,
              ).typography.body.color?.withOpacity(0.3),
            ),
            const SizedBox(height: 16),
            Text(
              '选择一个工具开始',
              style: MacosTheme.of(context).typography.body.copyWith(
                color: MacosTheme.of(
                  context,
                ).typography.body.color?.withOpacity(0.5),
              ),
            ),
          ],
        ),
      );
    }

    final isValid = _validateParameters();

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        // Header
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            border: Border(
              bottom: BorderSide(color: MacosTheme.of(context).dividerColor),
            ),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                widget.tool!.name,
                style: MacosTheme.of(
                  context,
                ).typography.title3.copyWith(fontWeight: FontWeight.bold),
              ),
              if (widget.tool!.description.isNotEmpty) ...[
                const SizedBox(height: 4),
                Text(
                  widget.tool!.description,
                  style: MacosTheme.of(context).typography.body.copyWith(
                    color: MacosTheme.of(
                      context,
                    ).typography.body.color?.withOpacity(0.7),
                  ),
                ),
              ],
            ],
          ),
        ),
        // Form fields
        Expanded(
          child: widget.tool!.parameters.isEmpty
              ? Center(
                  child: Text(
                    '无需参数',
                    style: MacosTheme.of(context).typography.body.copyWith(
                      color: MacosTheme.of(
                        context,
                      ).typography.body.color?.withOpacity(0.5),
                    ),
                  ),
                )
              : ListView.separated(
                  padding: const EdgeInsets.all(16),
                  itemCount: widget.tool!.parameters.length,
                  separatorBuilder: (context, index) =>
                      const SizedBox(height: 16),
                  itemBuilder: (context, index) {
                    return _buildParameterField(widget.tool!.parameters[index]);
                  },
                ),
        ),
        // Submit button
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            border: Border(
              top: BorderSide(color: MacosTheme.of(context).dividerColor),
            ),
          ),
          child: PushButton(
            controlSize: ControlSize.large,
            onPressed: isValid && !widget.isLoading ? widget.onSubmit : null,
            child: widget.isLoading
                ? const SizedBox(
                    height: 16,
                    width: 16,
                    child: ProgressCircle(radius: 8),
                  )
                : const Text('测试工具'),
          ),
        ),
      ],
    );
  }
}
